package com.aaa.system.aop;

import com.aaa.entity.OperLog;
import com.aaa.system.aop.annotation.Log;
import com.aaa.system.dao.OperLogDao;
import com.aaa.system.service.OperLogService;
import com.aaa.utils.WebUtil;
import com.alibaba.fastjson.JSON;
import org.apache.tomcat.jni.Local;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @program: his-open-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-03-23 11:22
 **/
@Component
@Aspect
public class OperLogAspect {

    //定义切点---
    @Pointcut(value = "@annotation(com.aaa.system.aop.annotation.Log)")
    private void pointcut(){}

    @Autowired
    private OperLogService operLogService;
    //定义通知
    @AfterReturning(value = "pointcut()",returning = "result")
    public void afterReturning( JoinPoint joinPoint,Object result){

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod(); //获取使用Log注解的方法对象
        Log log = method.getAnnotation(Log.class);

        String title = log.title();
        String businessType = log.business_type();
        String methodName = method.getName();
        HttpServletRequest request = WebUtil.getRequest();
        String requestMethod = request.getMethod();

        String operName="扁鹊";//可以从token钟获取
        String oper_url = request.getServletPath();
        String remoteAddr = request.getRemoteAddr();
        String oper_location=remoteAddr.startsWith("192.168.")?"内网IP":"外网IP";

        Object[] args = joinPoint.getArgs();
        String oper_param= JSON.toJSONString(args);
        String json_result=JSON.toJSONString(result);

        String status="0";
        Date oper_time=new Date();


        OperLog operLog=new OperLog(null,title,businessType,methodName,requestMethod,log.operator_type(),operName,oper_url,remoteAddr,oper_location,oper_param,json_result,status,"",oper_time);
        operLogService.insert(operLog);
    }
}
